package sms_practice;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
public class Producer extends Thread{
	// 定义ActivMQ的连接地址
	private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";// http://0.0.0.0:8161/ tcp://127.0.0.1:61616
	// 定义发送消息的队列名称
	private static final String QUEUE_NAME = "MessageFromSuperMarket";

	public void MessageSend() throws JMSException, SQLException {
		// 创建连接工厂
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
		// 创建连接
		Connection connection = activeMQConnectionFactory.createConnection();
		// 打开连接
		connection.start();
		// 创建会话
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建队列目标
		Destination destination = session.createQueue(QUEUE_NAME);
		// 创建一个生产者
		javax.jms.MessageProducer producer = session.createProducer(destination);
		// 创建模拟消息
		String path = "D:\\java\\workspaces\\Future\\sms_practice\\src\\main\\resources/goods.txt";// D:\Java\workspaces\sms-practice\src\main\resources
		File file = new File(path);
		BufferedReader reader = null;
		String tempString = null;

		try {

			reader = new BufferedReader(new FileReader(file));

			while ((tempString = reader.readLine()) != null) {

				TextMessage message = session.createTextMessage(tempString);
				// 发送消息
				producer.send(message);
				// 在本地打印消息
				System.out.println("Produce Sending:" + message.getText());

			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 关闭连接
		connection.close();
	}
	
	@Override
	public void run() { //Rewrite the run method
		try {
			this.MessageSend();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}